package cn.szzsi.common.sms;

import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.security.MessageDigest;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;
import java.util.UUID;

/**
 * 专信验证码
 */
public class SmsZhuanxinUtil {
    private static String active_status;
    private static String phone;
    private static String username;

    /**
     *
     * @param phone 手机号
     * @param sign 签名
     * @param content 内容
     */
    public static void sendToSms(String phone,String sign,String content) {
        String app_key = "nvevdwudrtnugo0jf6wxcq8jybrh9dwz";//系统给的app_key
        String app_secret = "7fd9e9cfcd9e75ced96781c04100608c9971";//系统给的app_secret
        String nonce_str = "youtyx";//用户名
        getPost(app_key, app_secret, nonce_str, phone, sign, content);
    }

    public static void getPost(String app_key,String app_secret,String nonce_str, String dest_id,String title,String content) {
        String shrot_message="http://api.5iliulang.com/api/v1/manySend"  ;
        HttpPost httpPost = new HttpPost(shrot_message)  ;
        String msg = getXmlInfo(app_key, app_secret, nonce_str, dest_id, title, content) ;
        HttpEntity entity = new StringEntity(msg, "UTF-8")  ;
        System.out.println("xmlInfo=" + msg)  ;
        httpPost.setEntity(entity)  ;
        CloseableHttpClient httpclient = HttpClients.createDefault()  ;
        CloseableHttpResponse responseBody ;
        try {
            // 获得响应消息码流
            responseBody =httpclient.execute(httpPost)  ;
            String result = EntityUtils.toString(responseBody.getEntity(), "UTF-8")  ;
            System.out.println("结果"+result)  ;
        } catch (Exception e) {
            e.printStackTrace()  ;
        } finally {
            try {
                httpclient.close()  ;
            } catch (IOException e) {
                e.printStackTrace()  ;
            }
        }
    }

    public static String getXmlInfo(String app_key,String app_secret,String nonce_str, String dest_id,String title,String content) {

        //时间戳
        String time_stamp=getTime() ;
        //批次号  以后改成自动的
        String batch_num=getBatch_num(nonce_str,time_stamp) ;
        //手机号，可以多个
        String[] dest_id_array=dest_id.split(",") ;
        //手机号对应个number
        String mission_num[] = new String [dest_id_array.length]  ;

        //短信类别   两种方案1：写逻辑做判断
        //         2：用户自己填写
        String sms_type="advert"  ;

        //为MD5加密使用
        String dest_id_md5=""  ;
        String mission_num_md5=""  ;

        //拼接XML
        StringBuilder sb = new StringBuilder()  ;
        sb.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>") ;
        sb.append("<xml>") ;
        sb.append("<head>") ;
        sb.append("<app_key>"+app_key+"</app_key>")  ;
        sb.append("<time_stamp>"+time_stamp+"</time_stamp>")  ;
        sb.append("<nonce_str>"+nonce_str+"</nonce_str>") ;

        for(int i=0;i<dest_id_array.length;i++){
            //0 代表前面补充0, 8代表长度为8,d 代表参数为正数型
            String str = String.format("%08d", i)  ;
            mission_num[i]="straycat"+str  ;
            dest_id_md5=dest_id_md5+"&dest_id="+dest_id_array[i] ;
            mission_num_md5=mission_num_md5+"&mission_num="+mission_num[i] ;
        }
        //计算sign
        String md="app_key="+app_key+"&batch_num="+batch_num+"&content="+"【"+title+"】"
                +content+dest_id_md5+mission_num_md5+"&nonce_str="+nonce_str+"&sms_type="+
                sms_type+"&time_stamp="+time_stamp+"&app_secret="+app_secret  ;

        String sign=MD5(md)  ;
        System.out.println("md5"+sign)  ;
        sb.append("<sign>"+sign+"</sign>") ;
        sb.append("</head>")  ;
        sb.append("<body>" ) ;
        sb.append("<dests>" ) ;
        //
        for(int i=0;i<dest_id_array.length;i++){
            sb.append("<dest>" ) ;
            sb.append("<mission_num>"+mission_num[i]+"</mission_num>") ;
            sb.append("<dest_id>"+dest_id_array[i]+"</dest_id>")  ;
            sb.append("</dest>")  ;
        }
        sb.append("</dests>")  ;
        sb.append("<batch_num>"+batch_num+"</batch_num>")  ;
        sb.append("<sms_type>"+sms_type+"</sms_type>") ;
        sb.append("<content>"+"【"+title+"】"+content+"</content>") ;
        sb.append("</body>")  ;
        sb.append("</xml>")  ;
        return sb.toString()  ;
    }

    public static String MD5(String inStr) {
        MessageDigest md5 = null  ;
        try {
            md5 = MessageDigest.getInstance("MD5")  ;
            byte[] byteArray = inStr.getBytes("utf-8") ;

            byte[] md5Bytes = md5.digest(byteArray)  ;

            StringBuffer hexValue = new StringBuffer()  ;

            for (int i = 0; i < md5Bytes.length; i++) {
                int val = ((int) md5Bytes[i]) & 0xff ;
                if (val < 16)
                    hexValue.append("0") ;
                hexValue.append(Integer.toHexString(val)) ;
            }

            return hexValue.toString()  ;
        } catch (Exception e) {
            System.out.println("e"+e.toString())  ;
            e.printStackTrace()  ;
            return ""  ;
        }
    }

    public static String getTime(){
        SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss")  ;
        return df.format(new Date())  ;
    }

    public static String getBatch_num(String nonce_str,String time_stamp) {
        Random r = new Random()  ;
        int i=r.nextInt(99999)  ;
        String Batch_num=nonce_str+time_stamp+String.valueOf(i)  ;
        return Batch_num ;
    }


    private static void UpdateToSql(int num, String title, String content, String phone, String username) {
        String[]  phones=phone.split(",");
        String[]  usernames=username.split(",");
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
        String createt_time =df.format(new Date());// new Date()为获取当前系统时间

        for (int i = 0; i <num ; i++) {
            String id = UUID.randomUUID().toString().replaceAll("-", "");
            String phone1 = phones[i].toString();
            String username1 = usernames[i].toString();
            // INSERT INTO `mall_sms_record` (`id`, `name`, `phone`, `content`, `createt_time`) VALUES ('3', '啊啊', '33', '啊啊', '订单')

            Record record = new Record().set("id", id).set("status", "1").set("name", username1).set("phone", phone1).set("content", content).set("createt_time", createt_time);
            Db.save("mall_sms_record", record);

        }

    }
}
